package com.deyinet.bdcms.controller;


import com.alibaba.fastjson.JSON;
import com.deyinet.bdcms.controller.dtoandapi.PswApi;
import com.deyinet.bdcms.core.common.VerifyCodeUtils;
import com.deyinet.bdcms.entity.*;
import com.deyinet.bdcms.service.ILogsService;
import com.deyinet.bdcms.service.ISysrolesService;
import com.deyinet.bdcms.service.ISysuserService;
import com.deyinet.bdcms.service.IsysConfService;
import com.deyinet.bdcms.tools.MD5ArithmeticUtils;
import com.deyinet.bdcms.tools.WebUtilify;
import com.deyinet.bdcms.tools.superUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Bacel on 2017/4/18.
 */
@Controller
@RequestMapping(value = "/sysmanage")
public class SysManageController {
    @Autowired
    private ISysuserService sysuserService;
    @Autowired
    private ILogsService logsService;
    @Autowired
    private IsysConfService sysConfService;
    @Autowired
    private ISysrolesService sysrolesService;

    @RequestMapping(value = "/LoginOut", method = RequestMethod.GET)
    public void LoginOut(final HttpSession session, final HttpServletResponse response)
            throws Exception {
        Enumeration em = session.getAttributeNames();
        while (em.hasMoreElements()) {
            session.removeAttribute(em.nextElement().toString());
        }
        response.sendRedirect("/sysmanage/login");
    }

    @RequestMapping(value = "/login")
    public void login() {
    }

    @RequestMapping(value = "/editpassword")
    @ResponseBody
    public Map<String, Object> editpassword(HttpSession session, @RequestBody PswApi api, HttpServletRequest request) {
        Sysuser user = WebUtilify.LoginUserinfo(request);
        Map<String, Object> info = new HashMap<>();
        Syslog log = new Syslog();
        if (!api.getNewPassword().equals(api.getNewPassword2())) {
            info.put("status", "error");
            info.put("content", "两个密码不一致");
            return info;
        }
        if (!MD5ArithmeticUtils.getMd5(api.getOldPassword()).equalsIgnoreCase(user.getPassword())) {
            info.put("status", "error");
            info.put("content", "原密码错误");
            return info;
        }
        user = sysuserService.get(user.getId());
        user.setPassword(MD5ArithmeticUtils.getMd5(api.getNewPassword()));
        sysuserService.updateT(user);
        log.setTitle("修改密码");//日志内容
        Enumeration em = session.getAttributeNames();
        while (em.hasMoreElements()) {
            session.removeAttribute(em.nextElement().toString());
        }

        Sysmodule sysmodule = new Sysmodule();
        sysmodule.setId(7);//根据数据库sysmodule表的对应的id去set
        log.setSysmoduleByModuleid(sysmodule);
        log.setSysuserByUserid(WebUtilify.LoginUserinfo(request));
        log.setContent(JSON.toJSONString(api));
        log.setCreatedate(new Timestamp(System.currentTimeMillis()));
        WebUtilify.WriteLog(request,log, logsService);

        info.put("status", "ok");
        info.put("content", "修改成功，请刷新页面重新登录");
        return info;
    }

    @RequestMapping(value = "/changepassword/edit")
    public void changepassword() {
    }

    @RequestMapping(value = "/userlogin", method = RequestMethod.POST)
    @ResponseBody
    public String userlogin(final HttpSession session, final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
        String usercode = request.getParameter("usercode");
        String userpws = request.getParameter("pws");
        String vcode = request.getParameter("vcode").toLowerCase();
        String sessionvcode = "";
        String errstr = "";
        if (session.getAttribute("verCode") != null) {
            sessionvcode = session.getAttribute("verCode").toString().toLowerCase();
            if (!userpws.equals("") && sessionvcode.equals(vcode) && !sessionvcode.equals("")) {
                String ret = "";
                Sysuser sysuser = new Sysuser();
                if (usercode.equals(superUser.getName()) && MD5ArithmeticUtils.getMd5(userpws).equalsIgnoreCase(superUser.getPassword())) {
                    sysuser.setName(superUser.getName());
                    sysuser.setRoleId(superUser.getRoleId());
                    sysuser.setId(superUser.getId());
                    session.setAttribute(WebUtilify.LoginUserKey, sysuser);
                } else {
                    sysuser.setName(usercode);
                    sysuser.setPassword(MD5ArithmeticUtils.getMd5(userpws));
                    List<Sysuser> list = sysuserService.findByExampleEq(sysuser);
                    if (list.size() > 0) {
                        session.setAttribute(WebUtilify.LoginUserKey, list.get(0));
                        session.removeAttribute("verCode");
                        errstr = "ok";
                    } else {
                        errstr = "帐号或密码有误";
                    }


                }
                ServletContext application = session.getServletContext();
                if (application.getAttribute("centerLng") == null || application.getAttribute("centerLat") == null) {
                    Sysconf sysconf = sysConfService.get(1);
                    String location = sysconf.getConfValue();
                    String[] locations = location.split(",");
                    application.setAttribute("centerLng", locations[0]);
                    application.setAttribute("centerLat", locations[1]);
                }
                if (application.getAttribute("adminRoleId") == null) {
                    application.setAttribute("adminRoleId", superUser.getRoleId());
                }
            } else {
                errstr = "验证码输入有误002";
            }
        } else {
            errstr = "验证码输入有误001";
        }
        if (errstr.equals("ok"))
            errstr = "";
        return WebUtilify.ReturnJsoninfo(errstr);
    }

    @RequestMapping(value = "/GetVerifyimg")
    public void GetVerifyimg(final HttpSession session, final HttpServletResponse response)
            throws Exception {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //存入会话session
        //删除以前的
        session.removeAttribute("verCode");
        session.setAttribute("verCode", verifyCode.toLowerCase());
        //生成图片
        int w = 100, h = 30;
        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
    }
}
